<template>
  <ContentWrap>
    <div :class="searchVisible ? 'flex flex-row flex-wrap mb-2' : 'flex flex-row flex-wrap'">
      <el-button v-hasRole="['shop_admin']" plain type="primary" @click="openForm('create')">
        <Icon class="mr-5px" icon="ep:plus" />
        新增
      </el-button>
      <el-button plain type="success" @click="searchVisible = !searchVisible">
        <Icon class="mr-5px" icon="ep:operation" />
        {{ searchVisible ? '关闭筛选' : '打开筛选' }}
      </el-button>
      <el-text type="info">
        <span class="ml-5px">{{ searchVisible ? '关闭以下筛选条件' : '点击打开筛选条件' }}</span>
      </el-text>
      <div class="flex-1"></div>
      <el-button @click="resetQuery">
        <Icon class="mr-5px" icon="ep:refresh" />
        刷新列表
      </el-button>
    </div>
    <el-form v-if="searchVisible" ref="searchFormRef" :model="tableData.searchParam" inline>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="tableData.searchParam.name"
          class="!w-240px"
          placeholder="请输入名称"
          clearable
          @keyup="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="创建时间">
          <el-date-picker
            v-model="tableData.searchParam.createTime"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div class="mt-[5px]">
      <el-tabs
        v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
        v-model="tableData.searchParam.type"
        @tab-click="handleTypeClick"
      >
        <el-tab-pane
          v-for="item in typeTabs"
          :key="item.value"
          :label="item.label"
          :name="item.value"
        />
      </el-tabs>
      <el-table :data="tableData.list" size="large" v-loading="tableData.loading">
        <template #empty>
          <span>{{ !tableData.loading ? '没有相关数据' : '' }}</span>
        </template>
        <el-table-column label="基本信息" min-width="160">
          <template #default="{ row }">
            <div class="flex flex-col items-start justify-start">
              <img
                class="w-[50px] h-[50px] mr-[10px] border border-solid border-gray-50"
                :src="row.picUrl || '/placeholder.png'"
                alt=""
              />
              <span>{{ row.name || '未知' }}</span>
              <span>{{ '适用于' + row.minPeople + '-' + row.maxPeople + '人' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
          label="所属店铺"
          min-width="120"
        >
          <template #default="{ row }">
            <div class="flex flex-col items-start justify-start">
              <img
                class="w-[50px] h-[50px] mr-[10px] border border-solid border-gray-50"
                :src="row.shop?.logo || '/placeholder.png'"
                alt=""
              />
              <span>{{ row.shop?.name || '未知' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格" min-width="120">
          <template #default="{ row }">
            <p v-if="row.originPrice > 0"
              >原价：<span class="line-through">¥{{ fenToYuan(row.originPrice) }}</span></p
            >
            <p v-if="row.price > 0"
              >销售价：<span class="text-orange-500">¥{{ fenToYuan(row.price) }}</span></p
            >
            <p v-if="row.price <= 0" class="text-red-500">请先加入团购产品</p>
            <p v-if="row.vipPrice > 0"
              >会员价：<span class="text-orange-500">¥{{ fenToYuan(row.vipPrice) }}</span></p
            >
            <!-- <p v-if="row.pointDeductCount > 0"
                ><span class="text-orange-500">{{ row.pointDeductCount }}</span> 积分抵
                <span class="text-orange-500">¥{{ fenToYuan(row.pointDeductPrice) }}</span></p
              >
              <p v-if="row.cryptocurrencyDeductCount > 0"
                ><span class="text-orange-500">{{ row.cryptocurrencyDeductCount }}</span> 联盟豆抵
                <span class="text-orange-500"
                  >¥{{ fenToYuan(row.cryptocurrencyDeductPrice) }}</span
                ></p
              > -->
          </template>
        </el-table-column>
        <el-table-column label="开关" align="left" width="230">
          <template #default="{ row }">
            <el-switch
              v-model="row.enabled"
              disabled
              :active-value="true"
              :inactive-value="false"
              active-text="已上架"
              inactive-text="已下架"
              inline-prompt
            />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column
          v-hasRole="['super_admin', 'platform_admin', 'tenant_admin', 'shop_admin']"
          label="操作"
          width="110"
          align="center"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              v-hasRole="['super_admin', 'platform_admin', 'tenant_admin', 'shop_admin']"
              link
              type="success"
              @click="openProductDrawer(scope.row.id)"
            >
              产品管理
            </el-button>
            <br />
            <el-button
              v-hasRole="['super_admin', 'platform_admin', 'tenant_admin', 'shop_admin']"
              link
              type="success"
              @click="openGiftDrawer(scope.row.id)"
            >
              赠品管理
            </el-button>
            <br />
            <el-button
              v-hasRole="['super_admin', 'platform_admin', 'tenant_admin', 'shop_admin']"
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
            >
              编辑
            </el-button>
            <br />
            <el-button
              v-hasRole="['shop_admin']"
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:limit="tableData.searchParam.pageSize"
        v-model:page="tableData.searchParam.pageNo"
        :total="tableData.total"
        @pagination="loadTableData"
      />
    </div>
  </ContentWrap>

  <PackageForm ref="formRef" @success="loadTableData" />
  <ProductDrawer ref="productDrawerRef" @refresh="loadTableData" />
  <GiftDrawer ref="giftDrawerRef" @refresh="loadTableData" />
</template>

<script lang="ts" setup name="GrouponPackage">
import * as GrouponPackageApi from '@/api/mall/promotion/groupon/package'
import { FormInstance, TabsPaneContext } from 'element-plus'
import { fenToYuan } from '@/utils'
import PackageForm from './PackageForm.vue'
import ProductDrawer from './product.vue'
import GiftDrawer from './gift.vue'
import { dateFormatter } from '@/utils/formatTime'

const { t } = useI18n()
const message = useMessage()

const searchVisible = ref(false)

const typeTabs = ref<any>([
  {
    label: '全部',
    value: ''
  },
  {
    label: '餐饮美食',
    value: 'food'
  },
  {
    label: '酒店住宿',
    value: 'hotel'
  },
  {
    label: '家政服务',
    value: 'housekeeping'
  },
  {
    label: '休闲娱乐',
    value: 'entertainment'
  }
])
const tableData = reactive({
  page: 1,
  limit: 10,
  total: 0,
  loading: true,
  list: [],
  searchParam: {
    pageNo: 1,
    pageSize: 10,
    type: '',
    name: '',
    createTime: []
  }
})

const handleTypeClick = (tab: TabsPaneContext) => {
  tableData.searchParam.type = tab.paneName + ''
  handleQuery()
}

const loadTableData = () => {
  if (!tableData.searchParam.type) {
    const { type, ...others } = tableData.searchParam
    tableData.searchParam = { ...others } as any
  }
  tableData.loading = true
  GrouponPackageApi.getPage({
    ...tableData.searchParam
  })
    .then((res: any) => {
      tableData.loading = false
      tableData.list = res.list
      tableData.total = res.total
    })
    .catch(() => {
      tableData.loading = false
    })
}

const searchFormRef = ref<FormInstance>()

const handleQuery = () => {
  tableData.searchParam.pageNo = 1
  loadTableData()
}

const resetQuery = () => {
  searchFormRef.value?.resetFields()
  tableData.searchParam = {
    pageNo: 1,
    pageSize: 10,
    type: '',
    name: '',
    createTime: []
  }
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number | string) => {
  formRef.value.open(type, id)
}
const productDrawerRef = ref()
const openProductDrawer = (id?: number | string) => {
  productDrawerRef.value.open(id)
}
const giftDrawerRef = ref()
const openGiftDrawer = (id?: number | string) => {
  giftDrawerRef.value.open(id)
}

const handleDelete = async (id: number | string) => {
  try {
    await message.delConfirm()
    await GrouponPackageApi.deleteById(id)
    message.success(t('common.delSuccess'))
    loadTableData()
  } catch {}
}

onMounted(() => {
  handleQuery()
})
</script>
